package com.ssm.blog.controller;

import com.github.pagehelper.PageInfo;
import com.ssm.blog.pojo.Notice;
import com.ssm.blog.service.NoticeService;
import com.ssm.blog.util.Funcs;
import com.ssm.blog.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Controller
@RequestMapping("/notice.html")
public class NoticeController {
    @Autowired
    private NoticeService noticeService;

    @RequestMapping(params = "act=list")
    @ResponseBody
    public Map<String, Object> NoticeTable(Notice criteria, Integer page, Integer rows) {
        PageInfo<Notice> pageInfo = noticeService.getNoticeList(criteria, page, rows);
        //key不可以改，页面上分页插件需要
        return JsonUtil.getDatagridPagerResult(pageInfo.getTotal(), pageInfo.getList());
    }

    @RequestMapping(params = "act=add")
    @ResponseBody
    public Map<String, Object> add(Notice notice) {
        notice.setUserId(1);
        noticeService.addNotice(notice);
        return JsonUtil.getSuccessMessage("添加成功", null);
    }

    @RequestMapping(params = "act=delete")
    @ResponseBody
    public Map<String, Object> delete(Integer id){
        noticeService.deleteNotice(id);
        return JsonUtil.getSuccessMessage("删除成功", null);
    }

    @Value("${NOTICE_IMAGE_DIR}")
    private String NOTICE_IMAGE_DIR;
    @Value("${NOTICE_IMAGE_URL}")
    private String NOTICE_IMAGE_URL;

    @RequestMapping(params = "act=upload")
    @ResponseBody
    public String upload(MultipartFile file) {
        try {
            String newFileName = Funcs.uploadFile(file, NOTICE_IMAGE_DIR);
            return "{\"error\":0,\"url\":\"" + NOTICE_IMAGE_URL + newFileName + "\"}";
        } catch (IOException e) {
            e.printStackTrace();
            return "{\"error\":1}";
        }
    }
}
